<template>
  <div class="index-cantainer">
    <el-card>
      <div class="table-head">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-button type="primary" @click="addRoles">添加角色</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="rolesList" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              :class="{'row-item':true,'row-bottom':true,'row-top':index==0}"
              v-for="(item,index) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="deleteRoles(scope.row.id,item.id)">{{item.authName}}</el-tag>
                <i class="iconfont iconcaret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  closable
                  :class="{'row-item':true,'row-top':index2!=0}"
                  v-for="(item1,index2) in item.children"
                  :key="item1.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRoles(scope.row.id,item1.id)"
                    >{{item1.authName}}</el-tag>
                    <i class="iconfont iconcaret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      closable
                      @close="deleteRoles(scope.row.id,item2.id)"
                    >{{item2.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" label="#" type="index"></el-table-column>
        <el-table-column align="center" label="角色名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="assignPermiss(scope.row)">分配权限</el-button>
            <el-button type="text" @click="deleteToRoles(scope.row.id)" style="color:red;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 修改角色弹窗 -->
      <el-dialog
        :title="rolesTitle"
        v-model="dialogVisible"
        width="600px"
        :before-close="handleClose"
      >
        <el-form :model="addFormData" :rules="rules" ref="ruleForm">
          <el-form-item prop="roleName" label="角色名称 :" class="form-items">
            <el-input v-model="addFormData.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述 :" class="form-items">
            <el-input v-model="addFormData.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="doConfirm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 分配权限弹窗 -->
      <el-dialog title="分配权限" v-model="permissionShow" width="800px">
        <el-tree
          :data="TreeData"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
          @check="handleChangeClick"
        ></el-tree>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="permissionShow = false">取 消</el-button>
            <el-button type="primary" @click="updateTreeChecked">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  V3_GetRolesListApi,
  V3_UpdateRolesApi,
  V3_AddRolesApi,
  V3_DeleteRolesApi,
  V3_DeleteRightsApi,
  V3_GetRightsApi,
  V3_UpdateRightsApi,
} from '../../api/request'
export default {
  setup() {
    const state = reactive({
      tableData: [],
      rolesList: [], //角色列表
      dialogVisible: false,
      addFormData: {
        roleName: '',
        roleDesc: '',
      },
      permissionShow: false,
      rolesTitle: '新增角色',
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        details: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
      TreeData: [], //权限树形结构
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      checkedKeys: [116], //已选中的权限
      nowData: {},
    })
    onMounted(() => {
      getRolesList()
    })
    // 分配权限按钮
    const assignPermiss = async (row) => {
      state.nowData = row
      row.children.forEach((e) => {
        e.children.forEach((e1) => {
          e1.children.forEach((e2) => {
            state.checkedKeys.push(e2.id)
          })
        })
      })
      const { data } = await V3_GetRightsApi()
      state.TreeData = data
      state.permissionShow = true
    }
    // 节点被选中时
    const handleChangeClick = (data, trrs) => {
      const { checkedKeys } = trrs
      state.checkedKeys = checkedKeys
    }

    const updateTreeChecked = async () => {
      const {
        nowData: { id },
        checkedKeys,
      } = state
      const res = await V3_UpdateRightsApi(id, { rids: checkedKeys.join(',') })
      console.log(res)
      if (res.meta.status == 200) {
        ElMessage.success('权限修改成功')
        getRolesList()
        state.permissionShow = false
      }
    }
    // 获取角色信息
    const getRolesList = () => {
      V3_GetRolesListApi().then((res) => {
        state.rolesList = res.data
      })
    }
    // 编辑角色
    const handleEdit = (row) => {
      state.rolesTitle = '编辑角色'
      const { roleDesc, roleName, id } = row
      Object.assign(state.addFormData, { roleDesc, roleName, id })
      state.dialogVisible = true
    }
    // 新增或编辑确认
    const doConfirm = async () => {
      const { roleDesc, roleName, id } = state.addFormData
      if (state.rolesTitle == '新增角色') {
        const res = await V3_AddRolesApi({ roleDesc, roleName })
        if (res.meta.status == 201) {
          ElMessage.success('新增成功')
          state.dialogVisible = false
          getRolesList()
        }
      } else {
        const res = await V3_UpdateRolesApi(id, { roleDesc, roleName })
        if (res.meta.status == 200) {
          ElMessage.success('修改成功')
          state.dialogVisible = false
          getRolesList()
        }
      }
    }
    // 删除分类
    const deleteRoles = async (rid, id) => {
      ElMessageBox.confirm('是否继续删除此权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await V3_DeleteRightsApi(rid, id)
          if (res.meta.status == 200) {
            getRolesList()
            ElMessage({
              type: 'success',
              message: '删除成功!',
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          })
        })
    }
    // 删除角色
    const deleteToRoles = (id) => {
      ElMessageBox.confirm('是否继续删除此角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await V3_DeleteRolesApi(id)
          if (res.meta.status == 200) {
            getRolesList()
            ElMessage({
              type: 'success',
              message: '删除成功!',
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          })
        })
    }
    // 添加角色
    const addRoles = () => {
      state.rolesTitle = '新增角色'
      state.dialogVisible = true
    }
    return {
      ...toRefs(state),
      handleEdit,
      doConfirm,
      addRoles,
      deleteRoles,
      deleteToRoles,
      assignPermiss,
      handleChangeClick,
      updateTreeChecked,
    }
  },
}
</script>

<style  lang="scss">
.el-tag {
  margin: 10px;
}
.row-item {
  display: flex;
  align-items: center;
}
.row-bottom {
  border-bottom: 1px solid #eee;
}
.row-top {
  border-top: 1px solid #eee;
}
.form-items {
  .el-form-item__content {
    display: flex !important;
  }
}
.iconerror {
  color: #999;
  cursor: pointer;
}

.table-head {
  margin: 0 0 20px;
}
</style>
